<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class SchoolAdminLog
 * @package App\Models
 * @author zjw
 */
class SchoolAdminLog extends Model
{
    public $timestamps = false;

    /**
     * @param $msg
     * @param SchoolAdmin|null $schoolAdmin
     * @return bool
     */
    public static function Log($msg, SchoolAdmin $schoolAdmin = null)
    {
        if (is_null($schoolAdmin)) {
            $schoolAdmin = \Auth::user();
        }
        $model = new self();
        $model->message = $msg;
        $model->action_ip = request()->getClientIp();
        $model->user_agent = request()->userAgent();
        $model->school_admin_id = $schoolAdmin->id;
        $model->action_time = date("Y-m-d H:i:s");
        return $model->save();
    }

    /**
     * @param $query
     * @param $name
     */
    public function scopeNameLike($query, $name)
    {
        $query->when($name, function ($query) use ($name) {
            $query->whereHas('schoolAdmin', function($query) use ($name) {
                $query->where('name', 'like', $name . '%');
            });
        });
    }

    /**
     * @param $query
     * @param $schoolId
     */
    public function scopeSchoolIs($query, $schoolId)
    {
        $query->when($schoolId, function ($query) use ($schoolId) {
            $query->whereHas('schoolAdmin', function ($query) use ($schoolId) {
                $query->where('school_id', $schoolId);
            });
        });
    }

    /**
     * @param $query
     * @param $schoolId
     */
    public function scopeSchoolIdIs($query, $schoolId)
    {
        $query->whereHas('schoolAdmin', function ($query) use ($schoolId) {
            $query->where('school_id', $schoolId);
        });
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function schoolAdmin()
    {
        return $this->belongsTo(SchoolAdmin::class);
    }
}
